package edu.kit.csl.tests.pisa.training;

/*
This file is part of the PISA Alignment Tool.

Copyright (C) 2013
Karlsruhe Institute of Technology
Cognitive Systems Lab (CSL)
Felix Stahlberg

PISA is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

PISA is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with PISA. If not, see <http://www.gnu.org/licenses/>.
*/

import static org.junit.Assert.*;
import junit.framework.Assert;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import edu.kit.csl.pisa.datatypes.Corpus;
import edu.kit.csl.pisa.datatypes.Dictionary;
import edu.kit.csl.pisa.models.SimpleModel;
import edu.kit.csl.pisa.training.EMTrainer;
import edu.kit.csl.pisa.training.Trainer;
import edu.kit.csl.pisa.ui.Configuration;

import edu.kit.csl.tests.pisa.KnightCorpus;

/**
 * Testing class for {@link edu.kit.csl.pisa.training.EMTrainer}.
 */
public class EMTrainerTest {
	
	private static Corpus corpus;
	private static Trainer trainer;
	private static SimpleModel model;
	
	private static final double DELTA = 0.1e-10;

	/**
	 * @throws java.lang.Exception
	 */
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		Configuration.getSingleton().set("model3Iterations", 1);
		Configuration.getSingleton().set("model3SuccStrategy", "id");
		Configuration.getSingleton().set("model3MaxStrategy", "id");
		Dictionary.getSingleton(Dictionary.SRC_DICT).clear();
		Dictionary.getSingleton(Dictionary.TRGT_DICT).clear();
	}
	
	/**
	 * @throws java.lang.Exception
	 */
	@Before
	public final void setUp() throws Exception {
		corpus = new KnightCorpus();
		model = new SimpleModel("model3");
		trainer = new EMTrainer(model);
		trainer.initializeTraining(corpus);
	}
	

	/**
	 * Test method for {@link edu.kit.csl.pisa.training.Trainer#train(edu.kit.csl.pisa.datatypes.Corpus)}.
	 */
	@Test
	public final void testTrain() {
		double init[] = {Math.log(0.5), Math.log(0.5)};
		assertArrayEquals(init, model.getParameterT()[0], DELTA);
		assertArrayEquals(init, model.getParameterT()[1], DELTA);
		trainer.train(corpus);
		assertArrayEquals(new double[]{
				Math.log(0.25), Math.log(0.75)
		}, model.getParameterT()[0], DELTA);
		assertArrayEquals(new double[]{
				Math.log(0.5), Math.log(0.5)
		}, model.getParameterT()[1], DELTA);
		for (int i = 0; i < 4; i++) {
			trainer.train(corpus);
		}
		// Translation probabilities should converge
		Assert.assertEquals(0, model.getParameterT()[0][1], 0.0001);
		Assert.assertEquals(0, model.getParameterT()[1][0], 0.0001);
	}

}
